package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Utils;
import com.example.forum.utils.StringUtils;
import com.example.forum.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")   //@NonNull是非空校验  @RequestParam是请求时指定的参数名
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //校验密码是否一致
        if(!password.equals(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //构造对象
        User user=new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //密码处理
        //1.生成盐
        String salt= UUIDUtils.UUID_32();
        //2.生成密码的密文
        String encryptPassword= MD5Utils.md5Salt(password,salt);
        //3.设置密码和盐
        user.setPassword(encryptPassword);
        user.setSalt(salt);

        //调用service
        userService.createNormalUser(user);

        return AppResult.success("注册成功");
    }


    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @ApiOperation("用户登录")
    @ResponseBody
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password){
        //调用service
        User user = userService.login(username, password);
        //在session中保存当前登录的用户信息
        //1. 获取session对象
        HttpSession session = request.getSession(true);
        //2. 把用户信息保存在session中
        session.setAttribute(AppConfig.SESSION_USER_KEY,user);
        //3. 返回成功
        return AppResult.success("登录成功");
    }

    /**
     * 退出登录
     * @return
     */
    @ApiOperation("退出登录")
    @ResponseBody
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        //获取session对象
        HttpSession session = request.getSession(false);
        //判断session是否有效
        if(session!=null){
            log.info("退出登录成功！！！"+session.toString());
            //销毁session
            session.invalidate();
        }
        //返回成功
        return AppResult.success("注销成功");
    }

    /**
     * 修改个人信息（头像，昵称等）
     * @param request
     * @return
     */
    @ApiOperation("获取用户详情")
    @ResponseBody
    @GetMapping("/info")                                                        // required = false表示为非必传参数
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id){
        //定义返回的user对象，若是后面要直接使用，则需赋值，比如：User user=null;
        User user;
        //非空校验
        if(id==null){
            //获取session
            HttpSession session = request.getSession(false);
            //从session中获取用户对象
            user= (User) session.getAttribute(AppConfig.SESSION_USER_KEY);
        }else{
            user=userService.selectById(id);
        }
        //返回结果
        return AppResult.success(user);
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult<User> modifyInfo(HttpServletRequest request,
                                      @ApiParam("姓名") @RequestParam(value = "username",required = false) String username,
                                      @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                      @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                      @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                      @ApiParam("电话号码") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                      @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark){
        //校验参数不能全部为空
        if(StringUtils.isEmpty(username) &&
                StringUtils.isEmpty(nickname) &&
                gender==null &&
                StringUtils.isEmpty(email) &&
                StringUtils.isEmpty(phoneNum) &&
                StringUtils.isEmpty(remark)){
            //返回提示
            return AppResult.failed("要修改的信息不能为空");
        }

        //获取session
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.SESSION_USER_KEY);

        //构造user对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        //调用service
        userService.modifyInfo(updateUser);
        //查询修改后用户数据
        user=userService.selectById(user.getId());
        //把user对象设置回session
        session.setAttribute(AppConfig.SESSION_USER_KEY,user);
        //返回结果
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //校验新密码和确认密码是否相同
        if(!newPassword.equals(passwordRepeat)){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //获取session中的用户
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.SESSION_USER_KEY);
        //调用service
        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        //销毁session
        if(session!=null){
            session.invalidate();
        }
        //返回结果
        return AppResult.success();
    }
}
